package com.ciwong.epaper.modules.homework.adapter;

import android.app.Activity;
import android.content.Context;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.homework.bean.PublishWorkRecords;
import com.ciwong.epaper.modules.me.adapter.PublishWorkListAdapter;
import com.ciwong.epaper.modules.me.bean.HomeWork;
import com.ciwong.epaper.modules.me.bean.HomeWorkContents;
import com.ciwong.epaper.modules.me.widget.SoftKeyBoardListener;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.widget.NoScrollListView;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TeacherWorkAdapter extends BaseExpandableListAdapter {

    /**
     * 添加类型：全部
     */
    public static final int ADD_TYPE_ALL = 0;

    /**
     * 添加类型：已添加
     */
    public static final int ADD_TYPE_YES = 1;

    /**
     * 添加类型：未添加
     */
    public static final int ADD_TYPE_NO = 2;

    private PublishWorkListAdapter publishWorkListAdapter;

    private int clientId;

    private long completeDate;

    /**
     * 添加类型
     */
    private int addType;

    private NoScrollListView publish_work_child;

    private List<PublishWorkRecords> pageList;

    private Context mContext;

    private TimePickerView pvTime;

    private RelativeLayout publish_work_parent_lay;

    public TeacherWorkAdapter(Context mContext, List<PublishWorkRecords> pageList) {
        this.mContext = mContext;
        this.pageList = pageList;
    }

    @Override
    public int getGroupCount() {
        return pageList == null ? 0 : pageList.size();
    }

    @Override
    public int getChildrenCount(int i) {
        return 1;
    }

    @Override
    public Object getGroup(int i) {
        return pageList == null ? 0 : pageList.get(i);
    }

    @Override

    public Object getChild(int i, int i1) {
        return 0 == pageList.get(i).getWorkList().size() ? null : pageList.get(i).getWorkList().get(0).getWorkContents().get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        GroupViewHolder groupViewHolder = null;
        if (null == view) {
            view = LayoutInflater.from(mContext).inflate(R.layout.activity_publish_work_parent, null);
            groupViewHolder = new GroupViewHolder();
            groupViewHolder.goto_book_icon = view.findViewById(R.id.goto_book_icon);
            groupViewHolder.publish_work_date = view.findViewById(R.id.publish_work_date);
            groupViewHolder.publish_work_member = view.findViewById(R.id.publish_work_member);
            groupViewHolder.publish_work_name = view.findViewById(R.id.publish_work_name);
            groupViewHolder.publish_work_type1 = view.findViewById(R.id.publish_work_type1);
            groupViewHolder.publish_work_type2 = view.findViewById(R.id.publish_work_type2);
            groupViewHolder.upe_effectiveDate_img = view.findViewById(R.id.upe_effectiveDate_img);
            groupViewHolder.work_effectiveDate = view.findViewById(R.id.work_effectiveDate);
            groupViewHolder.work_from_book = view.findViewById(R.id.work_from_book);
            groupViewHolder.work_status_lay = view.findViewById(R.id.work_status_lay);
            groupViewHolder.work_status_text = view.findViewById(R.id.work_status_text);
            groupViewHolder.work_type_image = view.findViewById(R.id.work_type_image);
            groupViewHolder.work_from_book_lay = (RelativeLayout) view.findViewById(R.id.work_from_book_lay);
            groupViewHolder.tea_work_alarm_clock = view.findViewById(R.id.tea_work_alarm_clock);
            groupViewHolder.publish_work_autorefuse = view.findViewById(R.id.publish_work_autorefuse);
            groupViewHolder.publish_work_autorefuse_edit = view.findViewById(R.id.publish_work_autorefuse_edit);
            groupViewHolder.upe_autorefuse_img = view.findViewById(R.id.upe_autorefuse_img);
            groupViewHolder.publish_work_autorefuse_lay = view.findViewById(R.id.publish_work_autorefuse_lay);
            groupViewHolder.publish_work_refuse_num_text = view.findViewById(R.id.publish_work_refuse_num_text);
            groupViewHolder.publish_work_refuse_num_lay = view.findViewById(R.id.publish_work_refuse_num_lay);
            view.setTag(groupViewHolder);
        } else {
            groupViewHolder = (GroupViewHolder) view.getTag();
        }
        setGroupView(i, groupViewHolder);
        return view;
    }

    @Override
    public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        if (null == view) {
            view = LayoutInflater.from(mContext).inflate(R.layout.activity_publish_work_child, null);
        }
        List<HomeWorkContents> workContents = new ArrayList<>();
        publish_work_child = (NoScrollListView) view;
        List<HomeWork> workList = pageList.get(i).getWorkList();
        for (int a = 0; a < workList.size(); a++) {
            List<HomeWorkContents> workContentList = workList.get(a).getWorkContents();
            for (int j = 0; j < workContentList.size(); j++) {
                workContentList.get(j).setReviceObject(workList.get(a).getReviceObject());
                workContentList.get(j).setWorkId(workList.get(a).getWorkId());
                workContentList.get(j).setSubjectId(workList.get(a).getSubjectId());
                workContents.add(workContentList.get(j));
            }
        }

        int studentCount = pageList.get(i).getWorkList().get(0).getTotalNum();
        publishWorkListAdapter = new PublishWorkListAdapter(mContext, workContents, studentCount, pageList.get(i));
        publish_work_child.setAdapter(publishWorkListAdapter);
        return view;
    }

    private void setGroupView(final int i, final GroupViewHolder groupViewHolder) {
        final PublishWorkRecords publishWorkRecords = pageList.get(i);
        if (null != publishWorkRecords) {
            long publishDate = publishWorkRecords.getPublishDate() * 1000;
            long effectiveDate = publishWorkRecords.getEffectiveDate() * 1000;
            long sendDate = publishWorkRecords.getSendDate() * 1000;
            final int autoRefusePercent = publishWorkRecords.getAutoRefusePercent();
            int autoRefuseMode = publishWorkRecords.getAutoRefuseMode();
            if (autoRefuseMode == 0) {
                groupViewHolder.publish_work_autorefuse_lay.setVisibility(View.GONE);
                groupViewHolder.publish_work_refuse_num_lay.setVisibility(View.GONE);
            } else {
                groupViewHolder.publish_work_autorefuse_lay.setVisibility(View.VISIBLE);
                groupViewHolder.publish_work_autorefuse.setText("退" + autoRefusePercent);

                groupViewHolder.publish_work_refuse_num_lay.setVisibility(View.VISIBLE);
                groupViewHolder.publish_work_refuse_num_text.setText(publishWorkRecords.getAutoRefuseNum() + "");

                groupViewHolder.upe_autorefuse_img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ToastUtil.INSTANCE.toastCenter(mContext, "低于满分的" + publishWorkRecords.getAutoRefusePercent() + "%自动退回");
                        groupViewHolder.publish_work_autorefuse_edit.setVisibility(View.VISIBLE);
                        groupViewHolder.publish_work_autorefuse_edit.setText(publishWorkRecords.getAutoRefusePercent() + "");
                        groupViewHolder.upe_autorefuse_img.setVisibility(View.GONE);
                        groupViewHolder.publish_work_autorefuse.setText("退");

                        setOnEditorAction(i, groupViewHolder.publish_work_autorefuse_edit, publishWorkRecords, groupViewHolder.upe_autorefuse_img, groupViewHolder.publish_work_autorefuse);
                    }
                });
            }
            if (0 != sendDate) {
                groupViewHolder.publish_work_date.setText(CWUtils.formatDate3(sendDate));
            } else {
                groupViewHolder.publish_work_date.setText(CWUtils.formatDate3(publishDate));
            }

            long nowTime = System.currentTimeMillis();
            if (nowTime > effectiveDate) {
                groupViewHolder.tea_work_alarm_clock.setVisibility(View.GONE);
                groupViewHolder.work_status_lay.setBackgroundResource(R.drawable.publish_work_status);
                groupViewHolder.work_status_text.setText("已结束");
                groupViewHolder.work_status_text.setTextColor(mContext.getResources().getColor(R.color.tea_work_eff_time));
            } else if (nowTime < effectiveDate && nowTime > sendDate) {
                groupViewHolder.tea_work_alarm_clock.setVisibility(View.GONE);
                groupViewHolder.work_status_lay.setBackgroundResource(R.drawable.publish_work_status2);
                groupViewHolder.work_status_text.setText("进行中");
                groupViewHolder.work_status_text.setTextColor(mContext.getResources().getColor(R.color.white));
            } else if (nowTime < effectiveDate && nowTime < sendDate && sendDate != 0) {
                groupViewHolder.tea_work_alarm_clock.setVisibility(View.VISIBLE);
                groupViewHolder.work_status_lay.setBackgroundResource(R.drawable.publish_work_status3);
                groupViewHolder.work_status_text.setText("未开始");
                groupViewHolder.work_status_text.setTextColor(mContext.getResources().getColor(R.color.white));
            }
            if (publishWorkRecords.getExamMode() == 2) {
                groupViewHolder.work_type_image.setImageResource(R.drawable.ce_shi);
            } else if (publishWorkRecords.getExamMode() == 1) {
                groupViewHolder.work_type_image.setImageResource(R.drawable.tea_work_type_computer);
            } else {
                groupViewHolder.work_type_image.setImageResource(R.drawable.training_publish_work);
            }

            groupViewHolder.upe_effectiveDate_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setTime(groupViewHolder, publishWorkRecords);
                    if (null != pvTime) {
                        pvTime.show();
                    }
                }
            });

            groupViewHolder.publish_work_name.setText(publishWorkRecords.getWorkName());
            groupViewHolder.publish_work_member.setText("作业成员: " + publishWorkRecords.getWorkList().get(0).getReviceObject());
            groupViewHolder.work_from_book.setText("来源书籍: " + publishWorkRecords.getBookName());
            if (publishWorkRecords.getExamMode() == 2) {
                groupViewHolder.work_effectiveDate.setText("进场截止: " + CWUtils.formatDate3(effectiveDate));
            }else{
                groupViewHolder.work_effectiveDate.setText("截止时间: " + CWUtils.formatDate3(effectiveDate));
            }
            if (publishWorkRecords.getExamMode() == 1 && publishWorkRecords.getWorkList().size() == 1 && publishWorkRecords.getWorkList().get(0).getWorkContents().size() == 1) {
                groupViewHolder.goto_book_icon.setVisibility(View.GONE);
                groupViewHolder.work_from_book_lay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });
            } else {
                groupViewHolder.goto_book_icon.setVisibility(View.VISIBLE);
                groupViewHolder.work_from_book_lay.setOnClickListener(new ViewOnClickListener() {
                    @Override
                    public void avertRepeatOnClick(View view) {
                        EpaperJumpManager.jumpToClassGrades((Activity) mContext, publishWorkRecords, R.id.go_back);
                    }

                });
            }
            if (publishWorkRecords.getSeeWorkMode() == 0) {
                groupViewHolder.publish_work_type1.setText(mContext.getString(R.string.see_work_before_eff));
            } else if (publishWorkRecords.getSeeWorkMode() == 2) {
                groupViewHolder.publish_work_type1.setText(mContext.getString(R.string.no_see_work_eff));
            } else {
                groupViewHolder.publish_work_type1.setText(mContext.getString(R.string.no_see_work_before_eff));
            }

            if (publishWorkRecords.getSubmitMode() == 0) {
                groupViewHolder.publish_work_type2.setText(mContext.getString(R.string.submit_work_before_eff));
            } else {
                groupViewHolder.publish_work_type2.setText(mContext.getString(R.string.no_submit_work_before_eff));
            }

        }
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    /**
     * 清空数据
     */
    public void clear() {
        if (pageList != null) {
            pageList.clear();
            //notifyDataSetChanged();
        }
    }

    //设置edittext监听
    public void setOnEditorAction(final int index, final EditText editText, final PublishWorkRecords publishWorkRecords, final ImageView imageView, final TextView textViewaudo) {
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                //判断是否是“完成”键
                int autoRefusePercent = 0;
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
                    if (null != editText.getText().toString() && !"".equals(editText.getText().toString())) {
                        autoRefusePercent = Integer.valueOf(editText.getText().toString());
                    }
                    setAutoRefusePercent(index, publishWorkRecords.getBatchId(), 3, publishWorkRecords.getBrandId(), "", autoRefusePercent, imageView, textViewaudo, editText);
                    //隐藏软键盘
                    InputMethodManager imm = (InputMethodManager) textView.getContext().getSystemService(
                            Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(textView.getApplicationWindowToken(), 0);
                    }
                    return true;
                }
                return false;
            }

        });

        SoftKeyBoardListener.setListener((Activity) mContext, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                //ToastUtil.INSTANCE.toastCenterSuccess("显示成功");
            }

            @Override
            public void keyBoardHide(int height) {
                int autoRefusePercent = 0;
                if (null != editText.getText().toString() && !"".equals(editText.getText().toString())) {
                    autoRefusePercent = Integer.valueOf(editText.getText().toString());
                }
                setAutoRefusePercent(index, publishWorkRecords.getBatchId(), 3, publishWorkRecords.getBrandId(), "", autoRefusePercent, imageView, textViewaudo, editText);
            }
        });

    }

    public void addAll(List<PublishWorkRecords> pageList) {
        if (this.pageList == null) {
            this.pageList = new ArrayList<PublishWorkRecords>();
        }
        if (pageList != null) {
            switch (addType) {
                case ADD_TYPE_ALL:
                    this.pageList.addAll(pageList);
                    break;

                case ADD_TYPE_YES:
                    for (PublishWorkRecords publishWorkRecords : pageList) {
//                        if (epaperInfo.isAdded()) {
                        this.pageList.add(publishWorkRecords);
//                        }
                    }
                    break;

                default:
                    for (PublishWorkRecords publishWorkRecords : pageList) {
//                        if (epaperInfo.isAdded()) {
                        this.pageList.add(publishWorkRecords);
//                        }
                    }
                    break;
            }
            notifyDataSetChanged();
        }
    }

    /**
     * 组视图助手
     */
    private class GroupViewHolder {
        /**
         * 作业日期
         */
        private TextView publish_work_date;

        /**
         * 作业状态
         */
        private RelativeLayout work_status_lay;

        /**
         * 作业状态
         */
        private TextView work_status_text;

        /**
         * 作业类型
         */
        private ImageView work_type_image;

        /**
         * 作业名
         */
        private TextView publish_work_name;

        /**
         * 作业成员
         */
        private TextView publish_work_member;

        /**
         * 来源书籍
         */
        private TextView work_from_book;

        private ImageView goto_book_icon;

        /**
         * 截止时间
         */
        private TextView work_effectiveDate;

        /**
         * 修改截止时间
         */
        private ImageView upe_effectiveDate_img;

        private TextView publish_work_type1;

        private TextView publish_work_type2;

        private RelativeLayout work_from_book_lay;

        private ImageView tea_work_alarm_clock;

        private TextView publish_work_autorefuse;

        private EditText publish_work_autorefuse_edit;

        private ImageView upe_autorefuse_img;
        private LinearLayout publish_work_autorefuse_lay;
        private TextView publish_work_refuse_num_text;
        private LinearLayout publish_work_refuse_num_lay;
    }

    private String getTimes(Date date) {//年月日时分格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }


    private void setTime(final GroupViewHolder groupViewHolder, final PublishWorkRecords publishWorkRecords) {
        //控制时间范围
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //获取当前年月日时分
        Integer year = selectedDate.get(Calendar.YEAR);
        Integer month = selectedDate.get(Calendar.MONTH);
        Integer day = selectedDate.get(selectedDate.DAY_OF_MONTH);
        //定时布置 默认晚当前时间一小时
        Integer hour = selectedDate.get(selectedDate.HOUR_OF_DAY);

        Integer minute = selectedDate.get(selectedDate.MINUTE);
        startDate.set(year, month, day, hour, minute);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2029, 11, 28, 23, 59);

        pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null

                completeDate = date.getTime() / 1000;
                if (publishWorkRecords.getExamMode() == 2) {
                    groupViewHolder.work_effectiveDate.setText("进场截止: " + CWUtils.formatDate3(date.getTime()));
                }else{
                    groupViewHolder.work_effectiveDate.setText("截止时间: " + CWUtils.formatDate3(date.getTime()));
                }
                BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
                if (null != verifyInfo) {
                    if (null != verifyInfo.getClientId() && !"".equals(verifyInfo.getClientId())) {
                        clientId = Integer.valueOf(verifyInfo.getClientId());
                    }
                }
                setEffectiveDate(publishWorkRecords.getBatchId(), 3, publishWorkRecords.getBrandId(), "", clientId, completeDate);
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, true, true, false})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .isCenterLabel(true)
                //.setDividerColor(mContext.getColor(R.color.favorites_title))
                //.setDividerColor(R.color.favorites_title)
                .setContentTextSize(16)//字号
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();
    }


    public void setEffectiveDate(long batchId, int state, long brandId, String wappid, long clientId, long effectiveDate) {
        EpaperDao.getInstance().setEffectiveDate(batchId, state, brandId, wappid, clientId, effectiveDate, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                ToastUtil.INSTANCE.toastCenterError(mContext.getString(R.string.upe_faild_try_later));
            }

            @Override
            public void failed(Object data) {
                ToastUtil.INSTANCE.toastCenterError(mContext.getString(R.string.upe_faild_try_later));
            }

            @Override
            public void success(Object data) {
                super.success(data);
            }
        });
    }

    public void setAutoRefusePercent(final int index, long batchId, int state, long brandId, String wappid, final int newAutoRefusePercent, final ImageView imageView, final TextView textView, final EditText editText) {
        EpaperDao.getInstance().setAutoRefusePercent(batchId, state, brandId, wappid, newAutoRefusePercent, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                ToastUtil.INSTANCE.toastCenterError(mContext.getString(R.string.upe_faild_try_later));
            }

            @Override
            public void failed(Object data) {
                ToastUtil.INSTANCE.toastCenterError(mContext.getString(R.string.upe_faild_try_later));
            }

            @Override
            public void success(Object data) {
                if (null != pageList && pageList.size() > 0) {
                    pageList.get(index).setAutoRefusePercent(newAutoRefusePercent);
                }
                editText.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
                textView.setText("退" + newAutoRefusePercent);
                super.success(data);
            }
        });
    }

}
